// Package car_park_api
// @Author Spume
// @Date 2024-12-19

package car_park_api

import (
	"encoding/json"
	"net/http"
	"strconv"
	"strings"
	"time"
)

// CarParkHandler HTTP处理器
type CarParkHandler struct {
	service CarParkService
}

// NewCarParkHandler 创建HTTP处理器
func NewCarParkHandler(service CarParkService) *CarParkHandler {
	return &CarParkHandler{
		service: service,
	}
}

// RegisterRoutes 注册路由
func (h *CarParkHandler) RegisterRoutes(mux *http.ServeMux) {
	// 健康检查
	mux.HandleFunc("GET /health", h.HealthCheck)
	
	// 停车场相关
	mux.HandleFunc("GET /parks", h.GetParks)
	
	// 月卡相关
	mux.HandleFunc("GET /month-cars", h.GetMonthCars)
	
	// 订单相关
	mux.HandleFunc("GET /orders", h.GetOrders)
	mux.HandleFunc("GET /orders/abnormal", h.GetAbnormalOrders)
}

// HealthCheck 健康检查
func (h *CarParkHandler) HealthCheck(w http.ResponseWriter, r *http.Request) {
	response := map[string]interface{}{
		"status":    "ok",
		"timestamp": time.Now().Unix(),
		"service":   "car_park_api",
	}
	h.writeJSONResponse(w, http.StatusOK, response)
}

// GetParks 获取停车场列表
func (h *CarParkHandler) GetParks(w http.ResponseWriter, r *http.Request) {
	// 解析查询参数
	input := &GetParksInput{
		AK:          r.URL.Query().Get("ak"),
		SK:          r.URL.Query().Get("sk"),
		CompanyCode: r.URL.Query().Get("companyCode"),
		Debug:       r.URL.Query().Get("debug") == "true",
	}
	
	// 解析分页参数
	if pageStr := r.URL.Query().Get("page"); pageStr != "" {
		if page, err := strconv.Atoi(pageStr); err == nil {
			input.Page = page
		}
	}
	if limitStr := r.URL.Query().Get("limit"); limitStr != "" {
		if limit, err := strconv.Atoi(limitStr); err == nil {
			input.Limit = limit
		}
	}
	
	// 调用服务
	parks, err := h.service.GetParks(r.Context(), input)
	if err != nil {
		h.writeErrorResponse(w, err)
		return
	}
	
	// 返回响应
	response := map[string]interface{}{
		"success": true,
		"data":    parks,
		"count":   len(parks),
	}
	h.writeJSONResponse(w, http.StatusOK, response)
}

// GetMonthCars 获取月卡用户列表
func (h *CarParkHandler) GetMonthCars(w http.ResponseWriter, r *http.Request) {
	// 解析查询参数
	input := &GetMonthCarsInput{
		AK:        r.URL.Query().Get("ak"),
		SK:        r.URL.Query().Get("sk"),
		CarNumber: r.URL.Query().Get("carNumber"),
		Debug:     r.URL.Query().Get("debug") == "true",
	}
	
	// 解析停车场编码列表
	if parkCodesStr := r.URL.Query().Get("parkCodes"); parkCodesStr != "" {
		input.ParkCodes = strings.Split(parkCodesStr, ",")
	}
	
	// 解析分页参数
	if pageIndexStr := r.URL.Query().Get("pageIndex"); pageIndexStr != "" {
		if pageIndex, err := strconv.Atoi(pageIndexStr); err == nil {
			input.PageIndex = pageIndex
		}
	}
	if pageSizeStr := r.URL.Query().Get("pageSize"); pageSizeStr != "" {
		if pageSize, err := strconv.Atoi(pageSizeStr); err == nil {
			input.PageSize = pageSize
		}
	}
	
	// 调用服务
	result, err := h.service.GetMonthCars(r.Context(), input)
	if err != nil {
		h.writeErrorResponse(w, err)
		return
	}
	
	// 返回响应
	response := map[string]interface{}{
		"success": true,
		"data":    result,
	}
	h.writeJSONResponse(w, http.StatusOK, response)
}

// GetOrders 获取临停订单列表
func (h *CarParkHandler) GetOrders(w http.ResponseWriter, r *http.Request) {
	// 解析查询参数
	input := &GetOrdersInput{
		AK:       r.URL.Query().Get("ak"),
		SK:       r.URL.Query().Get("sk"),
		ParkCode: r.URL.Query().Get("parkCode"),
		Debug:    r.URL.Query().Get("debug") == "true",
	}
	
	// 解析时间参数
	if startTimeStr := r.URL.Query().Get("startTime"); startTimeStr != "" {
		if startTime, err := strconv.ParseInt(startTimeStr, 10, 64); err == nil {
			input.StartTime = startTime
		}
	}
	if endTimeStr := r.URL.Query().Get("endTime"); endTimeStr != "" {
		if endTime, err := strconv.ParseInt(endTimeStr, 10, 64); err == nil {
			input.EndTime = endTime
		}
	}
	
	// 调用服务
	orders, err := h.service.GetOrders(r.Context(), input)
	if err != nil {
		h.writeErrorResponse(w, err)
		return
	}
	
	// 返回响应
	response := map[string]interface{}{
		"success": true,
		"data":    orders,
		"count":   len(orders),
	}
	h.writeJSONResponse(w, http.StatusOK, response)
}

// GetAbnormalOrders 获取异常订单列表
func (h *CarParkHandler) GetAbnormalOrders(w http.ResponseWriter, r *http.Request) {
	// 解析查询参数
	input := &GetAbnormalOrdersInput{
		AK:    r.URL.Query().Get("ak"),
		SK:    r.URL.Query().Get("sk"),
		Debug: r.URL.Query().Get("debug") == "true",
	}
	
	// 解析订单号列表
	if ordersStr := r.URL.Query().Get("orders"); ordersStr != "" {
		input.Orders = strings.Split(ordersStr, ",")
	}
	
	// 调用服务
	orders, err := h.service.GetAbnormalOrders(r.Context(), input)
	if err != nil {
		h.writeErrorResponse(w, err)
		return
	}
	
	// 返回响应
	response := map[string]interface{}{
		"success": true,
		"data":    orders,
		"count":   len(orders),
	}
	h.writeJSONResponse(w, http.StatusOK, response)
}

// writeJSONResponse 写入JSON响应
func (h *CarParkHandler) writeJSONResponse(w http.ResponseWriter, statusCode int, data interface{}) {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(statusCode)
	
	if err := json.NewEncoder(w).Encode(data); err != nil {
		http.Error(w, "Failed to encode response", http.StatusInternalServerError)
	}
}

// writeErrorResponse 写入错误响应
func (h *CarParkHandler) writeErrorResponse(w http.ResponseWriter, err error) {
	var statusCode int
	var errorCode string
	var message string
	
	// 根据错误类型设置状态码和错误信息
	switch e := err.(type) {
	case *InvalidParamsError:
		statusCode = http.StatusBadRequest
		errorCode = e.Code()
		message = e.Message()
	case *APIError:
		statusCode = http.StatusBadGateway
		errorCode = e.Code()
		message = e.Message()
	case *ParseError:
		statusCode = http.StatusInternalServerError
		errorCode = e.Code()
		message = e.Message()
	case *NetworkError:
		statusCode = http.StatusServiceUnavailable
		errorCode = e.Code()
		message = e.Message()
	default:
		statusCode = http.StatusInternalServerError
		errorCode = "INTERNAL_ERROR"
		message = err.Error()
	}
	
	response := map[string]interface{}{
		"success": false,
		"error": map[string]interface{}{
			"code":    errorCode,
			"message": message,
		},
		"timestamp": time.Now().Unix(),
	}
	
	h.writeJSONResponse(w, statusCode, response)
}